<?php
require_once 'phpmoko/lib/common.php';

class IP
{

	static function isIpPublic($ip)
	{
		$n = IP::ip2ulong($ip);
		if (!$n)
			return false;

		static $privateRanges = false;

		if (!$privateRanges) {
			$privateRanges = array( /*  */
				array('10.0.0.0', '10.255.255.255'),     /* RFC 1918 (private) */
				array('172.16.0.0', '172.31.255.255'),   /*     "              */
				array('192.168.0.0', '192.168.255.255'), /*     "              */
				array('0.0.0.0', '0.255.255.255'),       /* this network       */
				array('127.0.0.0', '127.255.255.255'),   /* loopback           */
			);
		}

		foreach ($privateRanges as $r)
			if (($n >= IP::ip2ulong($r[0])) && ($n <= IP::ip2ulong($r[1])))
				return false;

		return true;
	}

	static function getIPold()
	{
		if (isset($_SERVER["HTTP_CLIENT_IP"]))
			return $_SERVER["HTTP_CLIENT_IP"];

		if ((isset($_SERVER["HTTP_X_FORWARDED_FOR"])) && (IP::isIpPublic($_SERVER["HTTP_X_FORWARDED_FOR"])))
			return $_SERVER["HTTP_X_FORWARDED_FOR"];

		if (isset($_SERVER["REMOTE_ADDR"]))
			return $_SERVER["REMOTE_ADDR"];

		return "0.0.0.0";
	}

	static function checkIP($ip)
	{
		$vals = explode(".", $ip);
		$ipfinal = null;
		$cont = 0;
		foreach ($vals as $value) {
			$cont++;
			if (!is_numeric($value))
				return "0.0.0.0";

			if ($ipfinal != null)
				$ipfinal .= ".";

			$ipfinal .= number_format($value, 0);
		}

		if ($cont != 4)
			return "0.0.0.0";

		return $ipfinal;
	}

	static function getIP()
	{
		return IP::checkIP(IP::getIPold());
	}

	static function getCountryCode2()
	{
		$ip = IP::getIP();
		$linea = file("http://services1.groony.com/iptocountry.php?ip=" . IP::ip2ulong($ip));
		$code2 = explode(";", $linea[0]);

		return $code2[0];
	}

	static function ip2ulong($ip)
	{
		return sprintf("%u", ip2long($ip));
	}

	static function getHost()
	{
		return gethostbyaddr(IP::getIP());
	}

	static function getISP()
	{
		$ip = IP::getIP();
		$longisp = gethostbyaddr($ip);
		$isp = explode(".", $longisp);
		$isp = array_reverse($isp);
		if (count($isp) >= 2) {
			$ISP = $isp[1] . "." . $isp[0];
			return $ISP;
		}

		return "Desconocido";
	}
}
?>